<template>
  <div class="subject-list">
    <TeacherNavbar title="科目列表" />
    
    <!-- 操作按钮 -->
    <div style="margin-bottom: 10px;">
      <el-button type="primary" @click="handleImportQuestions">导入题库</el-button>
    </div>
    
    <!-- 科目列表表格 -->
    <el-table :data="subjectList" style="width: 100%" v-loading="loading">
      <el-table-column prop="subjectId" label="科目ID" width="80"></el-table-column>
      <el-table-column prop="subjectName" label="科目名称" width="150"></el-table-column>
      <el-table-column label="题型分布" width="200">
        <template #default="scope">
          选择题: {{ scope.row.choiceQuestionCount }}题<br>
          判断题: {{ scope.row.judgmentQuestionCount }}题<br>
          填空题: {{ scope.row.fillQuestionCount }}题
        </template>
      </el-table-column>
      <el-table-column label="分值设置" width="150">
        <template #default="scope">
          选择题: {{ scope.row.choiceQuestionScore }}分/题<br>
          判断题: {{ scope.row.judgmentQuestionScore }}分/题<br>
          填空题: {{ scope.row.fillQuestionScore }}分/题
        </template>
      </el-table-column>
      <el-table-column prop="timeLimit" label="考试时长(分钟)" width="120"></el-table-column>
      <el-table-column label="总分">
        <template #default="scope">
          {{
            scope.row.choiceQuestionCount * scope.row.choiceQuestionScore +
            scope.row.judgmentQuestionCount * scope.row.judgmentQuestionScore +
            scope.row.fillQuestionCount * scope.row.fillQuestionScore
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button size="small" @click="handleImportQuestions(scope.row)">手动导入</el-button>
          <el-button size="small" @click="handleImportExcel(scope.row)">Excel导入</el-button>
          <el-button size="small" type="primary" @click="handleGenerateAI(scope.row)">AI生题</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-if="total > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;">
    </el-pagination>

    <!-- AI生成题目对话框 -->
    <el-dialog v-model="aiDialogVisible" title="AI生成题目" width="600px">
      <el-form :model="aiForm" label-width="100px">
        <el-form-item label="生成数量">
          <el-input-number v-model="aiForm.count" :min="1" :max="20" label="生成题目数量"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="aiDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="generateAIQuestions" :loading="aiGenerating">生成</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- AI生成结果展示对话框 -->
    <el-dialog v-model="resultDialogVisible" title="AI生成的题目" width="800px" top="5vh">
      <el-table :data="generatedQuestions" max-height="400" style="width: 100%">
        <el-table-column prop="questionType" label="题型" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.questionType === 'choice'">选择题</el-tag>
            <el-tag v-else-if="scope.row.questionType === 'judgment' || scope.row.questionType === 'judgement'">判断题</el-tag>
            <el-tag v-else-if="scope.row.questionType === 'fill'">填空题</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="questionContent" label="题目内容" width="400"></el-table-column>
        <el-table-column prop="answer" label="答案" width="150"></el-table-column>
      </el-table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resultDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="saveAIQuestions">保存题目</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import TeacherAPI from '@/api/teacher'
import TeacherNavbar from '@/components/TeacherNavbar.vue'

export default {
  name: 'SubjectList',
  components: {
    TeacherNavbar
  },
  data() {
    return {
      subjectList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // AI生成题目相关数据
      aiDialogVisible: false,
      resultDialogVisible: false,
      aiGenerating: false,
      aiForm: {
        subjectId: '',
        count: 5
      },
      generatedQuestions: [],
      currentSubject: null
    }
  },
  created() {
    this.fetchSubjectList()
  },
  methods: {
    // 获取科目列表
    async fetchSubjectList() {
      this.loading = true
      try {
        const res = await TeacherAPI.getSubjectList(this.currentPage, this.pageSize)
        console.log('科目列表响应:', res)
        if (res.data.code === 200 && res.data.msg === 'success') {
          // 根据后端返回的数据结构进行适配
          this.subjectList = res.data.data.list || []
          this.total = res.data.data.total || 0
          // 更新当前页和页面大小
          this.currentPage = res.data.data.pageNum || this.currentPage
          this.pageSize = res.data.data.pageSize || this.pageSize
        } else {
          this.$message.error(res.data.message || '获取科目列表失败')
        }
      } catch (error) {
        console.error('获取科目列表失败:', error)
        this.$message.error('获取科目列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },

    // 每页数量改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchSubjectList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchSubjectList()
    },

    // 处理手动导入题库
    handleImportQuestions(subject) {
      // 跳转到手动导入题库页面，并传递科目ID作为查询参数
      this.$router.push({
        path: '/teacher/import-questions-manual',
        query: {
          subjectId: subject.subjectId
        }
      })
    },
    
    // 处理Excel导入题库
    handleImportExcel(subject) {
      // 跳转到Excel导入题库页面，并传递科目ID作为查询参数
      this.$router.push({
        path: '/teacher/import-questions-excel',
        query: {
          subjectId: subject.subjectId
        }
      })
    },

    // 处理AI生成题目
    handleGenerateAI(subject) {
      this.currentSubject = subject
      this.aiForm.subjectId = subject.subjectId
      this.aiForm.count = 5
      this.aiDialogVisible = true
    },

    // AI生成题目
    async generateAIQuestions() {
      if (!this.aiForm.subjectId || this.aiForm.count <= 0) {
        this.$message.error('参数不正确')
        return
      }

      this.aiGenerating = true
      try {
        const res = await TeacherAPI.importQuestionsAI(this.aiForm.subjectId, this.aiForm.count)
        if (res.data.code === 200 && res.data.msg === 'success') {
          this.generatedQuestions = res.data.data || []
          this.aiDialogVisible = false
          this.resultDialogVisible = true
        } else {
          this.$message.error('AI生成题目失败: ' + (res.data.message || '未知错误'))
        }
      } catch (error) {
        console.error('AI生成题目失败:', error)
        this.$message.error('AI生成题目失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.aiGenerating = false
      }
    },

    // 保存AI生成的题目
    async saveAIQuestions() {
      if (this.generatedQuestions.length === 0) {
        this.$message.error('没有可保存的题目')
        return
      }

      try {
        this.$message.info('正在保存题目，请稍候...')
        
        // 逐个保存题目
        let successCount = 0
        for (const question of this.generatedQuestions) {
          // 构造单个题目请求数据
          const questionData = {
            questionType: question.questionType,
            subjectId: this.aiForm.subjectId,
            questionContent: question.questionContent,
            answer: question.answer
          }
          
          // 发起导入请求
          const res = await TeacherAPI.importQuestionsManual(questionData)
          if (res.data.code === 200 && res.data.msg === 'success') {
            successCount++
          } else {
            this.$message.error(`题目"${question.questionContent.substring(0, 20)}..."保存失败: ` + (res.data.data || res.data.message))
            return
          }
        }
        
        this.$message.success(`成功保存${successCount}道题目`)
        this.resultDialogVisible = false
        // 重新加载科目列表以更新题目数量
        this.fetchSubjectList()
      } catch (error) {
        console.error('保存题目失败:', error)
        this.$message.error('保存题目失败: ' + (error.response?.data?.message || error.message))
      }
    }
  }
}
</script>

<style scoped>
.subject-list {
  padding: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>